﻿using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
// --- Copyright (c) notice NevoWeb ---
//  Copyright (c) 2008 SARL NevoWeb.  www.nevoweb.com. BSD License.
// Author: D.C.Lee
// ------------------------------------------------------------------------
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// ------------------------------------------------------------------------
// This copyright notice may NOT be removed, obscured or modified without written consent from the author.
// --- End copyright notice --- 


using DotNetNuke;
using DotNetNuke.Common;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using NEvoWeb.Modules.NB_Store;
using System.Xml;
using System.IO;

namespace NEvoWeb.Modules.NB_Store
{

    public partial class BackOfficeMenu : DotNetNuke.Framework.UserControlBase
    {

        #region "Private Members"
        protected string dnnctl = "";
        protected string spg = "";
        protected string etmode = "";
        protected bool skinurl = false;
        protected Entities.Modules.PortalModuleBase _Parent;
        #endregion
        protected string _MenuFilePath = "";

        #region "Properties"

        public string MenuFilePath
        {
            get { return _MenuFilePath; }
            set { _MenuFilePath = value; }
        }

        #endregion

        protected void Page_Load(object sender, System.EventArgs e)
        {
            NB_Store.SettingsController objSCtrl = new NB_Store.SettingsController();
            XmlDataDocument xmlDoc = new XmlDataDocument();

            _Parent = (DotNetNuke.Entities.Modules.PortalModuleBase)this.Parent;

            dnnctl = "";
            if ((Request.QueryString["ctl"] != null))
            {
                dnnctl = Request.QueryString["ctl"];
            }

            spg = "";
            if ((Request.QueryString["spg"] != null))
            {
                spg = Request.QueryString["spg"].ToLower();
            }

            etmode = "";
            if ((Request.QueryString["etmode"] != null))
            {
                etmode = Request.QueryString["etmode"].ToLower();
            }

            skinurl = false;
            if ((Request.QueryString["skinsrc"] != null))
            {
                skinurl = true;
            }

            string strCacheKey = "";
            strCacheKey = GetCacheKey("MainMenu.xml", _Parent.PortalId);

            if (!string.IsNullOrEmpty(strCacheKey))
            {
                if (DataCache.GetCache(strCacheKey) == null | GetStoreSettingBoolean(_Parent.PortalId, "debug.mode", "None"))
                {
                    if (string.IsNullOrEmpty(_MenuFilePath))
                    {
                        _MenuFilePath = _Parent.ModulePath;
                    }
                    xmlDoc.Load(Server.MapPath(_MenuFilePath + "xml/MainMenu.xml"));
                    MergePlugins(_Parent.PortalId, xmlDoc);
                    DataCache.SetCache(strCacheKey, xmlDoc, DateAndTime.DateAdd(DateInterval.Hour, 1, DateAndTime.Now));
                }
                else
                {
                    xmlDoc = (XmlDataDocument)DataCache.GetCache(strCacheKey);
                }

                string SkinSrc = "";
                if ((xmlDoc.SelectSingleNode("root/skin").Attributes("path") != null))
                {
                    SkinSrc = QueryStringEncode(DotNetNuke.Common.ResolveUrl(xmlDoc.SelectSingleNode("root/skin").Attributes("path").InnerText));
                }

                //add css file for menu
                AddCSSLink(xmlDoc);

                //check if skin is needed
                if (skinurl | string.IsNullOrEmpty(SkinSrc))
                {
                    buildMenu(xmlDoc);
                }
                else
                {
                    buildEnterButton(xmlDoc);
                    RegisterJS(_Parent.PortalId, "jquery.nbstorejquerycheck.js", _Parent.ModulePath, _Parent.Page);
                }

            }

        }

        private void buildEnterButton(XmlDataDocument xmlDoc)
        {
            HyperLink hyp = default(HyperLink);
            hyp = new HyperLink();

            string ResxCtrl = getAtt(xmlDoc, "root/resx", "name");
            string SkinSrc = QueryStringEncode(DotNetNuke.Common.ResolveUrl(getAtt(xmlDoc, "root/skin", "path")));
            string EnterCss = getAtt(xmlDoc, "root/enterbutton", "css");
            string EnterCssDiv = getAtt(xmlDoc, "root/enterbutton", "cssdiv");
            string ResourceKey = getAtt(xmlDoc, "root/enterbutton", "resourcekey");
            string EnterCtrl = getAtt(xmlDoc, "root/enterbutton", "defaultctrl");

            hyp.Text = getLocalTabText(ResourceKey, ResxCtrl);

            //only display button if menu module is being used, menu module should match resx module.
            if (!string.IsNullOrEmpty(hyp.Text) & ResxCtrl.StartsWith(this.Parent.GetType().BaseType.Name))
            {
                hyp.CssClass = EnterCss;
                hyp.NavigateUrl = NavigateURL(EnterCtrl, "mid=" + ((Entities.Modules.PortalModuleBase)this.Parent).ModuleId, "SkinSrc=" + SkinSrc);

                if (!string.IsNullOrEmpty(EnterCssDiv))
                {
                    EnterCssDiv = " class=\"" + EnterCssDiv + "\"";
                }

                plhTitle.Controls.Add(new LiteralControl("<div " + EnterCssDiv + ">"));
                plhTitle.Controls.Add(hyp);
                plhTitle.Controls.Add(new LiteralControl("</div>"));
            }

        }

        private XmlDataDocument MergePlugins(int PortalID, XmlDataDocument xmlDoc)
		{
			XmlDataDocument xmlPlug = new XmlDataDocument();
			NB_Store.SettingsController objCtrl = new NB_Store.SettingsController();
			NB_Store_SettingsInfo objSInfo = default(NB_Store_SettingsInfo);
			ArrayList aryList = null;
			XmlNode xmlNodToAdd = null;
			XmlNode xmlRoot = null;

			aryList = objCtrl.GetSettingList(PortalID, "None", true, "");

			foreach ( objSInfo in aryList) {
				if (objSInfo.SettingName.ToLower.EndsWith(".plugin")) {
					try {
						string TabControlName = null;
						string ModControlName = null;
						string ModControlSrc = null;
						//Add plugin to xml file.
						xmlPlug.LoadXml(objSInfo.SettingValue);
						//get the nod to be placed under.
						TabControlName = xmlPlug.SelectSingleNode("root/tabs/tab").Attributes("id").InnerXml;
						ModControlName = xmlPlug.SelectSingleNode("root/tabs/tab/subtab").Attributes("ctl").InnerXml;
						ModControlSrc = xmlPlug.SelectSingleNode("root/tabs/tab/subtab").Attributes("ctlsrc").InnerXml;

						xmlRoot = xmlDoc.SelectSingleNode("root/tabs/tab[@id='" + TabControlName + "']");


						if ((xmlRoot != null)) {
							//get nod to add
							xmlNodToAdd = xmlPlug.SelectSingleNode("root/tabs/tab/subtab");

							//append to xmldoc
							xmlRoot.AppendChild(xmlDoc.ImportNode(xmlNodToAdd, true));


							//add plugin to NB_Store_BackOffice
							DotNetNuke.Entities.Modules.ModuleControlInfo objModInfo = default(DotNetNuke.Entities.Modules.ModuleControlInfo);
							objModInfo = DotNetNuke.Entities.Modules.ModuleControlController.GetModuleControlByKeyAndSrc(_Parent.ModuleConfiguration.ModuleDefID, ModControlName, ModControlSrc);
							if (objModInfo == null) {
								objModInfo = new DotNetNuke.Entities.Modules.ModuleControlInfo();
								objModInfo.ControlKey = ModControlName;
								objModInfo.ControlSrc = ModControlSrc;
								objModInfo.ControlTitle = ModControlName;
								objModInfo.ControlType = SecurityAccessLevel.Edit;
								objModInfo.HelpURL = "";
								objModInfo.IconFile = "";
								objModInfo.ModuleControlID = Null.NullInteger;
								objModInfo.ModuleDefID = _Parent.ModuleConfiguration.ModuleDefID;
								objModInfo.SupportsPartialRendering = false;
								objModInfo.ViewOrder = 0;

								DotNetNuke.Entities.Modules.ModuleControlController.AddModuleControl(objModInfo);

							}

						}


					} catch (Exception ex) {
						ex.HelpLink = "Plugin Failed to Load: " + objSInfo.SettingName;
						LogException(ex);
						// plugin failed to load
					}

				}
			}

			return xmlDoc;
		}

        private void buildMenu(XmlDataDocument xmlDoc)
        {
            XmlNode nod = null;
            XmlNodeList nodList = null;
            string strLink = null;
            string TabName = "";
            string SubTabName = "";


            //set resx
            string ResxCtrl = getAtt(xmlDoc, "root/resx", "name");
            string SkinSrc = QueryStringEncode(DotNetNuke.Common.ResolveUrl(getAtt(xmlDoc, "root/skin", "path")));
            string TitleCss = getAtt(xmlDoc, "root/css", "titlediv");
            string TabCss = getAtt(xmlDoc, "root/css", "tabdiv");
            string TabulCss = getAtt(xmlDoc, "root/css", "tabul");
            string TabliCss = getAtt(xmlDoc, "root/css", "tabli");
            string TabliActiveCss = getAtt(xmlDoc, "root/css", "tabliactive");

            string SubTabCss = getAtt(xmlDoc, "root/css", "subtabdiv");
            string SubTabulCss = getAtt(xmlDoc, "root/css", "subtabul");
            string SubTabliCss = getAtt(xmlDoc, "root/css", "sublitabli");
            string SubTabliActiveCss = getAtt(xmlDoc, "root/css", "sublitabliactive");


            if (!string.IsNullOrEmpty(TabCss))
                TabCss = " class=\"" + TabCss + "\"";
            if (!string.IsNullOrEmpty(TabulCss))
                TabulCss = " class=\"" + TabulCss + "\"";
            if (!string.IsNullOrEmpty(TabliCss))
                TabliCss = " class=\"" + TabliCss + "\"";
            if (!string.IsNullOrEmpty(TabliActiveCss))
                TabliActiveCss = " class=\"" + TabliActiveCss + "\"";
            if (!string.IsNullOrEmpty(SubTabCss))
                SubTabCss = " class=\"" + SubTabCss + "\"";
            if (!string.IsNullOrEmpty(SubTabulCss))
                SubTabulCss = " class=\"" + SubTabulCss + "\"";
            if (!string.IsNullOrEmpty(SubTabliCss))
                SubTabliCss = " class=\"" + SubTabliCss + "\"";
            if (!string.IsNullOrEmpty(SubTabliActiveCss))
                SubTabliActiveCss = " class=\"" + SubTabliCss + "\"";
            if (!string.IsNullOrEmpty(TitleCss))
                TitleCss = " class=\"" + TitleCss + "\"";

            //build tab menu
            nodList = xmlDoc.SelectNodes("root/tabs/tab");
            strLink = "<div  " + TabulCss + ">";
            strLink += "<table  " + TabCss + "><tr>";


            foreach (XmlNode nod_loopVariable in nodList)
            {
                nod = nod_loopVariable;

                if (checkDisplayRoles(nod))
                {


                    XmlNodeList nList = null;
                    bool ActiveParent = false;
                    nList = nod.SelectNodes("subtab[@ctl='" + dnnctl + "']");

                    if ((nList != null))
                    {
                        if (nList.Count > 0)
                        {
                            ActiveParent = true;
                        }
                    }

                    if (dnnctl == nod.Attributes["ctl"].InnerText)
                    {
                        ActiveParent = true;
                    }

                    string iconURL = nod.Attributes["image"].InnerText;

                    if (!iconURL.ToLower().StartsWith("~/desk"))
                    {
                        //need to add module path
                        iconURL = ((Entities.Modules.PortalModuleBase)this.Parent).ModulePath + iconURL;
                    }
                    else
                    {
                        iconURL = DotNetNuke.Common.ResolveUrl(iconURL);
                    }


                    if (ActiveParent)
                    {
                        TabName = getLocalTabText(nod.Attributes["text"].InnerText, ResxCtrl);
                        if (string.IsNullOrEmpty(SkinSrc))
                        {
                            strLink += "<td " + TabliActiveCss + " ><a href=\"" + NavigateURL(nod.Attributes["ctl"].InnerText, "mid=" + ((Entities.Modules.PortalModuleBase)this.Parent).ModuleId, nod.Attributes["param"].InnerText) + "\" ><img src=\"" + iconURL + "\" alt=\"\" border=\"0\" align=\"absmiddle\" /> " + getLocalTabText(nod.Attributes["text"].InnerText, ResxCtrl) + "</a></td>";
                        }
                        else
                        {
                            strLink += "<td " + TabliActiveCss + " ><a href=\"" + NavigateURL(nod.Attributes["ctl"].InnerText, "mid=" + ((Entities.Modules.PortalModuleBase)this.Parent).ModuleId, nod.Attributes["param"].InnerText, "SkinSrc=" + SkinSrc) + "\" ><img src=\"" + iconURL + "\" alt=\"\" border=\"0\" align=\"absmiddle\" /> " + getLocalTabText(nod.Attributes["text"].InnerText, ResxCtrl) + "</a></td>";
                        }
                    }
                    else
                    {
                        if (nod.Attributes["ctl"].InnerText == "EXIT")
                        {
                            //Exit Menu
                            strLink += "<td " + TabliCss + " ><a href=\"" + NavigateURL() + "\" ><img src=\"" + iconURL + "\" alt=\"\" border=\"0\"  align=\"absmiddle\" /> " + getLocalTabText(nod.Attributes["text"].InnerText, ResxCtrl) + "</a></td>";

                        }
                        else
                        {
                            if (string.IsNullOrEmpty(SkinSrc))
                            {
                                strLink += "<td " + TabliCss + " ><a href=\"" + NavigateURL(nod.Attributes["ctl"].InnerText, "mid=" + ((Entities.Modules.PortalModuleBase)this.Parent).ModuleId, nod.Attributes["param"].InnerText) + "\" ><img src=\"" + iconURL + "\" alt=\"\" border=\"0\" align=\"absmiddle\" /> " + getLocalTabText(nod.Attributes["text"].InnerText, ResxCtrl) + "</a></td>";
                            }
                            else
                            {
                                strLink += "<td " + TabliCss + " ><a href=\"" + NavigateURL(nod.Attributes["ctl"].InnerText, "mid=" + ((Entities.Modules.PortalModuleBase)this.Parent).ModuleId, nod.Attributes["param"].InnerText, "SkinSrc=" + SkinSrc) + "\" ><img src=\"" + iconURL + "\" alt=\"\" border=\"0\" align=\"absmiddle\" /> " + getLocalTabText(nod.Attributes["text"].InnerText, ResxCtrl) + "</a></td>";
                            }
                        }
                    }
                }
            }
            strLink += "</tr></table>";
            strLink += "</div>";

            //Me.Controls.Add(New LiteralControl(strLink))
            plhTabMenu.Controls.Add(new LiteralControl(strLink));

            //select 1st subtab nod with ctl attribute
            nod = xmlDoc.SelectSingleNode("root/tabs/tab/subtab[@ctl=\"" + dnnctl + "\"]");
            //get get children of parent
            strLink = "<div  " + SubTabulCss + ">";
            strLink += "<table  " + SubTabCss + "><tr>";

            if ((nod != null))
            {
                foreach (XmlNode nod2 in nod.ParentNode.ChildNodes)
                {

                    if (checkDisplayRoles(nod2))
                    {
                        string iconURL = nod2.Attributes["image"].InnerText;

                        if (!iconURL.ToLower().StartsWith("~/desk"))
                        {
                            //need to add module path
                            iconURL = ((Entities.Modules.PortalModuleBase)this.Parent).ModulePath + iconURL;
                        }
                        else
                        {
                            iconURL = DotNetNuke.Common.ResolveUrl(iconURL);
                        }


                        if (IsActiveSubTab(nod2.Attributes["ctl"].InnerText, dnnctl, nod2.Attributes["param"].InnerText))
                        {
                            SubTabName = getLocalTabText(nod2.Attributes["text"].InnerText, ResxCtrl);
                            if (string.IsNullOrEmpty(SkinSrc))
                            {
                                strLink += "<td " + SubTabliActiveCss + " ><a href=\"" + NavigateURL(nod2.Attributes["ctl"].InnerText, "mid=" + ((Entities.Modules.PortalModuleBase)this.Parent).ModuleId, nod2.Attributes["param"].InnerText) + "\" ><img src=\"" + iconURL + "\" alt=\"\" border=\"0\"  align=\"absmiddle\"/> " + getLocalTabText(nod2.Attributes["text"].InnerText, ResxCtrl) + "</a></td>";
                            }
                            else
                            {
                                strLink += "<td " + SubTabliActiveCss + " ><a href=\"" + NavigateURL(nod2.Attributes["ctl"].InnerText, "mid=" + ((Entities.Modules.PortalModuleBase)this.Parent).ModuleId, nod2.Attributes["param"].InnerText, "SkinSrc=" + SkinSrc) + "\" ><img src=\"" + iconURL + "\" alt=\"\" border=\"0\"  align=\"absmiddle\"/> " + getLocalTabText(nod2.Attributes["text"].InnerText, ResxCtrl) + "</a></td>";
                            }
                        }
                        else
                        {
                            if (nod2.Attributes["ctl"].InnerText == "HELP")
                            {
                                //Help Buton
                                strLink += "<td " + SubTabliCss + " ><a href=\"" + ((Entities.Modules.PortalModuleBase)this.Parent).ModulePath + "documentation/Documentation.html\" target=\"_blank\" ><img src=\"" + iconURL + "\" alt=\"\" border=\"0\"  align=\"absmiddle\" /> " + getLocalTabText(nod2.Attributes["text"].InnerText, ResxCtrl) + "</a></td>";
                            }
                            else
                            {
                                if (string.IsNullOrEmpty(SkinSrc))
                                {
                                    strLink += "<td " + SubTabliCss + " ><a href=\"" + NavigateURL(nod2.Attributes["ctl"].InnerText, "mid=" + ((Entities.Modules.PortalModuleBase)this.Parent).ModuleId, nod2.Attributes["param"].InnerText) + "\" ><img src=\"" + iconURL + "\" alt=\"\" border=\"0\"  align=\"absmiddle\"/> " + getLocalTabText(nod2.Attributes["text"].InnerText, ResxCtrl) + "</a></td>";
                                }
                                else
                                {
                                    strLink += "<td " + SubTabliCss + " ><a href=\"" + NavigateURL(nod2.Attributes["ctl"].InnerText, "mid=" + ((Entities.Modules.PortalModuleBase)this.Parent).ModuleId, nod2.Attributes["param"].InnerText, "SkinSrc=" + SkinSrc) + "\" ><img src=\"" + iconURL + "\" alt=\"\" border=\"0\"  align=\"absmiddle\"/> " + getLocalTabText(nod2.Attributes["text"].InnerText, ResxCtrl) + "</a></td>";
                                }
                            }
                        }
                    }
                }
            }
            strLink += "</tr></table>";
            strLink += "</div>";

            //Me.Controls.Add(New LiteralControl(strLink))
            plhSubTabMenu.Controls.Add(new LiteralControl(strLink));


            if (string.IsNullOrEmpty(SubTabName))
            {
                strLink = "<div " + TitleCss + ">" + TabName + "</div>";
            }
            else
            {
                strLink = "<div " + TitleCss + ">" + TabName + " - " + SubTabName + "</div>";
            }

            //Me.Controls.Add(New LiteralControl(strLink))
            plhTitle.Controls.Add(new LiteralControl(strLink));

        }

        private bool IsActiveSubTab(string MenuCtrl, string dnnCtrl, string menuaparam)
        {
            bool blnActive = false;

            if (string.IsNullOrEmpty(spg) & string.IsNullOrEmpty(etmode))
            {
                if (MenuCtrl == dnnCtrl)
                {
                    blnActive = true;
                }
            }
            else
            {
                // shipping control being used, test param to get active ctrl
                if (!string.IsNullOrEmpty(spg))
                {
                    if (MenuCtrl == dnnCtrl & menuaparam.EndsWith(spg))
                    {
                        blnActive = true;
                    }
                }

                // setting control being used, test param to get active ctrl
                if (!string.IsNullOrEmpty(etmode))
                {
                    if (MenuCtrl == dnnCtrl & menuaparam.EndsWith(etmode))
                    {
                        blnActive = true;
                    }
                }

            }

            return blnActive;
        }

        private string getAtt(XmlDataDocument xmlDoc, string XPath, string AttName)
        {
            if ((xmlDoc.SelectSingleNode(XPath).Attributes(AttName) != null))
            {
                return xmlDoc.SelectSingleNode(XPath).Attributes(AttName).InnerText;
            }
            else
            {
                return "";
            }
        }


        private string getLocalTabText(string TabText, string ResourceCtrl)
        {
            string rtnMsg = null;
            rtnMsg = Localization.GetString(Strings.Replace(TabText, " ", "_"), Services.Localization.Localization.GetResourceFile(this.Parent, ResourceCtrl));
            if (string.IsNullOrEmpty(rtnMsg))
                rtnMsg = TabText;
            return rtnMsg;
        }


        private void AddCSSLink(XmlDataDocument xmlDoc)
        {
            string LinkFile = getAtt(xmlDoc, "root/css", "path");
            if (!string.IsNullOrEmpty(LinkFile))
            {
                System.Web.UI.HtmlControls.HtmlGenericControl oLink = new System.Web.UI.HtmlControls.HtmlGenericControl("link");
                oLink.Attributes["rel"] = "stylesheet";
                oLink.Attributes["media"] = "screen";
                oLink.Attributes["type"] = "text/css";
                oLink.Attributes["href"] = LinkFile;
                Control oCSS = this.Page.FindControl("CSS");
                if ((oCSS != null))
                {
                    oCSS.Controls.Add(oLink);
                }
            }
        }

        private bool checkDisplayRoles(XmlNode nod)
        {
            bool blnAdd = false;

            //check roles
            if ((nod.Attributes["roles"] != null) & !((Entities.Modules.PortalModuleBase)this.Parent).UserInfo.IsSuperUser & !((Entities.Modules.PortalModuleBase)this.Parent).UserInfo.IsInRole("Administrators"))
            {
                string[] ManagerRoles = null;
                ManagerRoles = nod.Attributes["roles"].InnerText.Split(',');
                for (int lp = 0; lp <= ManagerRoles.GetUpperBound(0); lp++)
                {
                    if (((Entities.Modules.PortalModuleBase)this.Parent).UserInfo.IsInRole(ManagerRoles[lp]))
                    {
                        blnAdd = true;
                    }
                }

            }
            else
            {
                blnAdd = true;
            }
            return blnAdd;

        }
        public BackOfficeMenu()
        {
            Load += Page_Load;
        }

    }

}